package com.clh.seckill.rabbitmq;

import com.alibaba.fastjson.JSON;
import com.clh.seckill.config.TopicRabbitMQConfig;
import com.clh.seckill.pojo.SeckillMessage;
import com.clh.seckill.pojo.SeckillOrder;
import com.clh.seckill.pojo.User;
import com.clh.seckill.service.IGoodsService;
import com.clh.seckill.service.IOrderService;
import com.clh.seckill.vo.GoodsVo;
import com.clh.seckill.vo.RespBeanEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

/**
 * @Author cailinhu
 * @Description 消费者
 * @Date 2022/1/12 10:46
 * @Version 1.0
 */
@Component
@Slf4j
public class MQReceiver {
    /**
     * 队列下单操作！！
     * @param message
     */
    @Autowired
    IGoodsService goodsService;
    @Autowired
    RedisTemplate redisTemplate;
    @Autowired
    IOrderService orderService;
    @RabbitListener(queues = TopicRabbitMQConfig.QUEUE_NAME)
    public void receiver(Message message){
        log.info("消费者拿到的消息："+message);
        String meg = new String(message.getBody());
        SeckillMessage seckillMessage = JSON.parseObject(meg, SeckillMessage.class);
        User user = seckillMessage.getUser();
        Long goodsId = seckillMessage.getGoodsId();
        GoodsVo goodsVo = goodsService.findGoodsById(goodsId);
        if (goodsVo.getSeckillCount()<1)return;
        SeckillOrder seckillOrder= (SeckillOrder)redisTemplate.opsForValue().get("order:"+user.getId()+":"+goodsId);
        if (seckillOrder!=null){
            log.info("用户已经抢过一次了！"+message);
            return;
        }
        //开始真正的下单
        orderService.createSeckillOrder(user,goodsVo);
    }

}
